<?php



declare (strict_types=1);



namespace app\stores\controller\miniapp;



use app\beautiful\logic\ConDataLogic;

use app\beautiful\logic\MemberCouponLogic;

use app\beautiful\model\CouponModel;



use app\beautiful\model\member\MemberModel;

use app\beautiful\model\miniapp\RecommendAppModel;

use app\beautiful\model\StyleModel;

use app\BaseController;

use app\common\helper\open\OpenPlatformMiniappHelper;

use app\common\logic\TokenLogic;

use app\common\model\RegisterLogsModel;

use app\beautiful\logic\PartnerLogic;

use TencentCloud\Cds\V20180420\Models\DbauditTypesInfo;

use think\facade\Db;



class Main extends BaseController {

    public function getRecommendMiniapps(){

        $datas = RecommendAppModel::where([

            ['shop_id','=', $this->request->shopId],

            ['is_delete','=',0]

        ])->order(['recommend_app_id'=>'desc'])->limit($this->request->limit)->select()->toArray();

        return $this->success([

            'miniapps' => $datas

        ]);

    }



    //下放风格基本配置

    public function init() {

        $shopId = $this->request->shopId;

        $style = cache('miniapp_style' . $shopId);

        if (empty($style)) {

            $miniappStyle = StyleModel::find($shopId);

            if (null === $miniappStyle) {

                return $this->error('暂未设置小程序风格');

            }

            $style = $miniappStyle->style;

            cache('miniapp_style' . $shopId, $style, 86400);

        }

        $coupon = Db::name('beautiful_coupon')

            ->where(['type_id'=>4,'status'=>1,'is_delete'=>0,'shop_id'=>$shopId])->value('coupon_money');

        if(!$coupon){

            $coupon = Db::name('beautiful_coupon')

                ->where(['type_id'=>2,'status'=>1,'is_delete'=>0,'shop_id'=>$shopId])->value('coupon_money');

        }

        $return['style']    = $style;

        $return['shopInfo'] = $this->request->miniapp;

        $return['coupon'] = intval($coupon);

        return $this->success($return);

    }

    //登录

    public function passport() {

        $code = $this->request->param('code');

        $encryptedData = $this->request->param('encryptedData','');

        $iv = $this->request->param('iv','');

        $from_type = $this->request->param('from_type',1);

        if(empty($code) || empty($encryptedData) || empty($iv)){

            return $this->error('登录授权解析失败#01');

        }
        $Openplatform = new OpenPlatformMiniappHelper();
        if($from_type==2){
            $this->request->shopId=35;
        }
        $datas = $Openplatform->setShopId($this->request->shopId)->getUserInfo([
            'code'          => $code,
            'encryptedData' => $encryptedData,
            'iv'            => $iv,
        ]);
        if (false === $datas) {

            return $this->error('登录授权解析失败');

        }

        $pid = $this->request->param('pid/d');

        $today = date('Y-m-d', $this->request->time()); 

        $is_new = false;
        if($from_type==1){//单店版授权登录
            if (null === $member = MemberModel::where([

                    ['shop_id', '=', $this->request->shopId],

                    ['mobile', '=', $datas['mobile']],

                    ['is_delete','=',0]

                ])->find()) {
                $member = new MemberModel();

                $member->shop_id = $this->request->shopId;

                $member->mobile = $datas['mobile'];

                $member->level_id = 0;

                $member->open_id = $datas['openid'];

                $member->nick_name = 'V'.$this->request->shopId.date('md').mt_rand(100000,999999); //防止有特殊字的用户


                $member->save();

                //新用户的券

                $new_member_coupon_data=CouponModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['type_id','=',2],

                    ['status','=',1],

                    ['is_delete','=',0],

                    ['start_time','<=',$today],

                    ['end_time','>=',$today],

                ])->order(['update_time'=>'desc','add_time'=>'desc'])

                    ->limit(5)

                    ->field('coupon_id,name,coupon_money,money_limit,valid_bg_time,valid_end_time')

                    ->select()->toArray();

                if(!empty($new_member_coupon_data)){

                    $member_coupon_logic= new MemberCouponLogic($this->request->shopId,$member->member_id);

                    foreach ($new_member_coupon_data as $coupon){

                        $member_coupon_logic->getCoupon($coupon,2,1,0);

                    }

                }

                //送优惠券

                if(!empty($pid)){

                    $invitation_coupon_data=CouponModel::where([

                        ['shop_id','=',$this->request->shopId],

                        ['type_id','=',4],

                        ['status','=',1],

                        ['is_delete','=',0],

                        ['start_time','<=',$today],

                        ['end_time','>=',$today],

                    ])->order(['update_time'=>'desc','add_time'=>'desc'])

                        ->limit(5)

                        ->field('coupon_id,name,coupon_money,money_limit,valid_bg_time,valid_end_time')

                        ->select()->toArray();

                    if(!empty($invitation_coupon_data)){

                        $coupon = $invitation_coupon_data[array_rand($invitation_coupon_data,1)] ?? [];

                        if(!empty($coupon)){

                            //被邀请送券

                            $member_coupon_logic= new MemberCouponLogic($this->request->shopId,$member->member_id);

                            $member_coupon_logic->getCoupon($coupon,2,10,0);

                            //邀请送券

                            $member_coupon_logic= new MemberCouponLogic($this->request->shopId,$pid);

                            $member_coupon_logic->getCoupon($coupon,2,9,0);

                        }

                    }

                }



                //插入注册日志

                $register_logs = new RegisterLogsModel();

                $register_logs->shop_id=$this->request->shopId;

                $register_logs->mobile=$member->mobile;

                $register_logs->save();

                $is_new = true;

            }else{ //非新用户不更新Pid 了

                if(empty($member->open_id)){

                    $member->open_id=$datas['openid'];

                    $member->save();

                }

            }
        }elseif ($from_type==2){//平台版授权登录
//            if($datas['mobile']==15283829512){
//                $datas['mobile'] = 13981069996;
//            }
            if (null === $member = MemberModel::where([

                    ['shop_id', '=', 0],

                    ['mobile', '=', $datas['mobile']],

                    ['is_delete','=',0]

                ])->find()) {
                $member = new MemberModel();

                $member->member_num = memberNum(8);

                $member->shop_id = 0;

                $member->mobile = $datas['mobile'];

                $member->level_id = 0;

                $member->open_id = $datas['openid'];

                $member->nick_name = 'V'.(int)date('m').date('d').mt_rand(100000,999999); //防止有特殊字的用户

                $member->from_type = $from_type;
                
                $member->save();

                //插入注册日志

                $register_logs = new RegisterLogsModel();

                $register_logs->shop_id=0;

                $register_logs->mobile=$member->mobile;

                $register_logs->save();

                $is_new = true;

            }else{ //非新用户不更新Pid 了

                if(empty($member->open_id)){

                    $member->open_id=$datas['openid'];

                    $member->save();

                }
                if($datas['mobile']){

                    $member->mobile=$datas['mobile'];

                    $member->save();

                }

            }
        }

        //合伙人绑定

        if(!empty($pid)){

            $PartnerLogic = new PartnerLogic($this->request->shopId);

            $PartnerLogic->bindPartner($member->member_id, $pid,$is_new);

        }

       

        $return = [];

        $return['token'] = TokenLogic::getMiniToken($member->member_id);

        return $this->success($return);

    }



    public function getHomeData()

    {

        $params=$this->request->param('params/a',[]);

        if(empty($params)) return $this->success([]);

        foreach ($params as $param){

            if(!isset($param['key'])) return $this->error('参数错误');

            if(empty($param['key'])) return $this->error('参数错误');

            if(!isset($param['num'])) return $this->error('参数错误');

            if(empty($param['num']) || $param['num']<=0 || $param['num']>10) return $this->error('参数错误');

        }

        $ConDataLogic = new ConDataLogic($this->request->shopId,$this->request->memberId);

        $datas=$ConDataLogic->getData($params);

        return $this->success(['datas'=>$datas]);

    }

}

